package com.example.peibei.ui.fragment;

import android.Manifest;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.dingtao.common.bean.HomeCateTwo;
import com.dingtao.common.bean.Order;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDFragment;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.bean.CityBean;
import com.example.peibei.service.presenter.HomeBannerCatePresenter;
import com.example.peibei.service.presenter.HomeOrderPresenter;
import com.example.peibei.service.presenter.RecommendMemberPresenter;
import com.example.peibei.ui.HomeChild2Head;
import com.example.peibei.ui.activity.LoginActivity;
import com.example.peibei.ui.activity.MoreRecommendActivity;
import com.example.peibei.ui.activity.OrderDetailActivity;
import com.example.peibei.ui.activity.PersonInfoActivityTwo;
import com.example.peibei.ui.adapter.HomeOrderListAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tencent.mmkv.MMKV;
import com.yxp.permission.util.lib.PermissionUtil;
import com.yxp.permission.util.lib.callback.PermissionResultCallBack;
import com.zhouwei.mzbanner.holder.MZHolderCreator;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

public class HomeChildFragment2 extends WDFragment {
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    String type = "";
    private HomeOrderListAdapter adapter;
    private HomeChild2Head head;
    private HomeOrderPresenter homeOrderPresenter;
    private RecommendMemberPresenter recommendMemberPresenter;
    private HomeBannerCatePresenter homeBannerCatePresenter;
    private SPUtils spUtils;
    private String cityCode = "";
    private String cityName = "";
    public AMapLocationClient mLocationClient = null;

    public HomeChildFragment2 setType(String type) {
        this.type = type;
        return this;
    }

    @Override
    public String getPageName() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_child;
    }

    @Override
    protected void initView() {

        head = new HomeChild2Head(getContext());

        adapter = new HomeOrderListAdapter();
        adapter.setOnItemClickListener((adapter, view, position) -> {
            String token = spUtils.getString(SpConstant.USER_TOKEN);
            if (TextUtils.isEmpty(token)){
                intent(LoginActivity.class);
                return;
            }
            Order.RecordsDTO order = (Order.RecordsDTO) adapter.getData().get(position);
            String publishOrderId = order.getPublishOrderId();
            Bundle bundle = new Bundle();
            bundle.putString("publishOrderId", publishOrderId);
            intent(OrderDetailActivity.class, bundle);
        });
        adapter.addChildClickViewIds(R.id.iv_head);
        adapter.setOnItemChildClickListener((adapter, view, position) -> {
            String token = spUtils.getString(SpConstant.USER_TOKEN);
            if (TextUtils.isEmpty(token)){
                intent(LoginActivity.class);
                return;
            }
            if (view.getId() == R.id.iv_head) {
                Order.RecordsDTO order = (Order.RecordsDTO) adapter.getData().get(position);
                Bundle bundle = new Bundle();
                bundle.putString("mid", order.getMid());
                intent(PersonInfoActivityTwo.class, bundle);
            }
        });
        adapter.setHeaderView(head.getView());
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        rv.setAdapter(adapter);

        refreshLayout.setOnRefreshListener(refreshLayout -> onRefreshStart());
        refreshLayout.setOnLoadMoreListener(refreshLayout -> onLoadMoreStart());

        spUtils = new SPUtils(getActivity(), SpConstant.USER_TOKEN);
        if ("0".equals(type)){
            getPermission();
            cityCode = spUtils.getString(SpConstant.CITY_CODE);
            cityName = spUtils.getString(SpConstant.CITY_NAME);
        }

        //获取数据
        homeOrderPresenter = new HomeOrderPresenter(new OrderCall());
        recommendMemberPresenter = new RecommendMemberPresenter(new RecommendMemberCall());
        homeBannerCatePresenter = new HomeBannerCatePresenter(new HomeCall());
        onRefreshStart();
    }

    public void updateData(String cc, String cn) {
        cityCode = cc;
        cityName = cn;
        if (homeOrderPresenter != null) {
            homeOrderPresenter.reqeust(true, "", type, cc, cn);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        head.showAndHideCZServe();
    }

    private void getPermission() {
        String[] PERMISSIONS = {
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                Manifest.permission.ACCESS_FINE_LOCATION
        };
        PermissionUtil.getInstance().request(getActivity(), PERMISSIONS,
                new PermissionResultCallBack() {
                    @Override
                    public void onPermissionGranted() {
                        // 当所有权限的申请被用户同意之后,该方法会被调用
                        head.showLocal(false);

                        //隐私政策合规
                        AMapLocationClient.updatePrivacyShow(getActivity().getApplicationContext(), true, true);
                        AMapLocationClient.updatePrivacyAgree(getActivity().getApplicationContext(), true);
                        //初始化定位
                        try {
                            mLocationClient = new AMapLocationClient(getActivity().getApplicationContext());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        //声明定位回调监听器
                        AMapLocationListener mLocationListener = new AMapLocationListener() {
                            @Override
                            public void onLocationChanged(AMapLocation aMapLocation) {
                                Log.i("answer", aMapLocation.getCity());//城市信息
                                Log.i("answer", aMapLocation.getCityCode());//城市信息
                                spUtils.putString(SpConstant.CITY_NAME, aMapLocation.getCity());
                                spUtils.putString(SpConstant.CITY_CODE, aMapLocation.getCityCode());
                                CityBean cityBean = new CityBean(aMapLocation.getCity(), aMapLocation.getCityCode());
                                EventBus.getDefault().post(cityBean);
                                updateData(aMapLocation.getCityCode(),aMapLocation.getCity());
                            }
                        };
                        //设置定位回调监听
                        mLocationClient.setLocationListener(mLocationListener);
                        AMapLocationClientOption option = new AMapLocationClientOption();
                        option.setOnceLocation(true);

                        //给定位客户端对象设置定位参数
                        mLocationClient.setLocationOption(option);
                        //启动定位
                        mLocationClient.startLocation();
                    }

                    @Override
                    public void onPermissionGranted(String... strings) {

                    }

                    @Override
                    public void onPermissionDenied(String... permissions) {
                        head.showLocal(type.equals("0"));
                    }

                    @Override
                    public void onRationalShow(String... permissions) {
                        head.showLocal(type.equals("0"));
                    }

                });
    }

    public void onRefreshStart() {
        homeBannerCatePresenter.reqeust();
        recommendMemberPresenter.reqeust(true);
        homeOrderPresenter.reqeust(true, "", type, cityCode, cityName);
    }

    public void onLoadMoreStart() {
        homeOrderPresenter.reqeust(false, "", type, cityCode, cityName);
    }


    class OrderCall implements DataCall<Order> {
        View view;
        @Override
        public void success(Order data, Object... args) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            //添加列表并刷新
            if (homeOrderPresenter.getPage() == 1) {
                adapter.setNewInstance(data.getRecords());
            }else {
                adapter.addData(data.getRecords());
            }
            if (adapter.getData().isEmpty()){
                view = LayoutInflater.from(getContext()).inflate(R.layout.empty_home_child,null,false);
                adapter.setFooterView(view);
            }else {
                if (view != null)
                adapter.removeFooterView(view);
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }
    }

    class RecommendMemberCall implements DataCall<Order> {

        @Override
        public void success(Order data, Object... args) {
            head.setRecommendMemberData(data.getRecords(),true);
        }

        @Override
        public void fail(ApiException e, Object... args) {

        }
    }

    class HomeCall implements DataCall<HomeCateTwo> {

        @Override
        public void success(HomeCateTwo data, Object... args) {
            head.setHomeCateData(data.getCategory(),true);
            head.setBannerData(data.getBanner());
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }
}
